from Controller.BaseController import BaseController
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from Common.Client import Client
from Common.Campaign import Campaign
from Utility import FormData
from Utility import UserRole
from Utility import ViewName
from Utility import IsEmptyString
#import Configuration
#from urllib import quote 
from Utility import TemplateValueName
from google.appengine.ext.db import BadKeyError

class CreateCampaignController(BaseController):
    """
    Let company admin create Campaign and assign Campaign to a client
    """
    def get(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.User,"/create/campaign"):
            return
        # make sure current user is admin account
        # list all groups which belong the company which is associated with current user
        c = u.Ref_Company
        template_values = {'Clients': c.Clients, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        self.Render(ViewName.D_CREATECAMPAIGN, template_values)
    
    
    def post(self):
        u = self.GetCurrentUser()
        
        # must be company admin
        if not self.VerifyCurrentUserRole(u, UserRole.User,"/create/campaign"):
            return
        
        campaignName = self.request.get(FormData.CAMPAIGN_NAME)
        clientKey = self.request.get(FormData.CLIENT_KEY)
        c = u.Ref_Company        
        template_values = {'Clients': c.Clients, "CompanyName": c.CompanyName, "CompanyKey":c.key()}
        
        if IsEmptyString(clientKey):
            template_values[TemplateValueName.ERROR_MESSAGE]="Client id is invalid"
            return self.Render(ViewName.D_CREATECAMPAIGN, template_values)
        
        
        try:
            client = Client.get(clientKey)
        except BadKeyError:
            template_values[TemplateValueName.ERROR_MESSAGE]="Client id is invalid"
            return self.Render(ViewName.D_CREATECAMPAIGN, template_values)
        
        try:
            campaign = Campaign(parent = client,
                     key_name=campaignName,
                     CampaignName=campaignName,
                     Ref_Client = client)
            campaign.TransactionPut()
            template_values[TemplateValueName.SUCCESS_MESSAGE]="New Campaign, " + campaignName + ", was created successfully!"
        except DuplicatedInstanceError:
            template_values[TemplateValueName.ERROR_MESSAGE]="Campaign, "+campaignName + ", already exists!"

        self.Render(ViewName.D_CREATECAMPAIGN, template_values)
